package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyComment;
import cn.wolfcode.wolf2w.query.StrategyCommentQuery;
import cn.wolfcode.wolf2w.respository.StrategyCommentRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import cn.wolfcode.wolf2w.service.IStrategyCommentService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {


    @Autowired
    private StrategyCommentRepository strategyCommentRepository;
    @Autowired
    private MongoTemplate template;

    @Override
    public void save(StrategyComment strategyComment) {
        strategyComment.setId(null);
        strategyComment.setCreateTime(new Date());
        strategyCommentRepository.save(strategyComment);
    }

    @Override
    public StrategyComment get(String id) {
        return strategyCommentRepository.findById(id).orElse(null);
    }


    @Override
    public List<StrategyComment> list() {
        return strategyCommentRepository.findAll();
    }

    @Override
    public Page<StrategyComment> query(StrategyCommentQuery qo) {

        Query query = new Query();

        if (StringUtils.hasLength(qo.getStrategyId())) {
            query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        }

        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");

        return DBHelper.query(template, StrategyComment.class, query, pageable);
    }

    @Override
    public void commentThumb(String cid, String uid) {

        // 获取点赞id集合
        StrategyComment comment = this.get(cid);
        List<String> idList = comment.getThumbuplist();

        // 判断uid是否在集合中
        if (idList.contains(uid)) {
            // 在的话 点赞+1 移除已经点赞
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            idList.remove(uid);
        } else {
            // 不在的话 点赞数+1 添加已经点赞
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            idList.add(uid);
        }

        // 更新
        strategyCommentRepository.save(comment);
    }
}


































































